﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Conversion_Script
{
    class Output
    {
        static Random rnd = new Random();
        static string SubFolder(string outputdir, string subdir)
        {
            return outputdir + "\\" + subdir + "\\";
        }
        static public string FileName(string outputdir, string subdir, string Label, int Time)
        {
            return SubFolder(outputdir, subdir) + "\\" + Label + Time + ".txt";
        }
        static public string FileName(string outputdir, string subdir, string Label)
        {
            return SubFolder(outputdir, subdir) + "\\" + Label + ".txt";
        }
        static public string FileName(string outputdir, string Label)
        {
            return outputdir + "\\" + Label + ".txt";
        }
        static string OutputFileName(string outputdir, string subdir, string Label)
        {
            if (System.IO.Directory.Exists(outputdir) == false) System.IO.Directory.CreateDirectory(outputdir);
            if (System.IO.Directory.Exists(SubFolder(outputdir, subdir)) == false) System.IO.Directory.CreateDirectory(outputdir + "\\" + subdir);
            return FileName(outputdir, subdir, Label);
        }
        static string OutputFileName(string outputdir, string subdir, string Label, int Time)
        { 
            if (System.IO.Directory.Exists(outputdir) == false) System.IO.Directory.CreateDirectory(outputdir);
            if (System.IO.Directory.Exists(SubFolder(outputdir, subdir)) == false) System.IO.Directory.CreateDirectory(outputdir + "\\" + subdir);
            return FileName(outputdir, subdir, Label, Time);
        }
        public static void WriteSumAreas(string[] Labels, string Label)
        {
            string filename = Settings.Get(KeyWords.Scenarioname) + "\\" + Label + ".txt";
            System.Console.WriteLine("Writing\t" + filename);
            List<string> Content = new List<string>();
            string hdr = "Time\t";
            foreach (string landuse in Labels) hdr += landuse + "\t";
            Content.Add(hdr);

            int t = 0;
            while ( t < Settings.GetSimulationLength())
            {
                float[] values = new float[Landscape.LandUseNames.Length];
                ASCII LandUse = new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), KeyWords.LandUse, KeyWords.LandUse, t));
                ASCII a = new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), Label, Label, t));

                for (int r = 0; r < Landscape.LandUseMap.Nrows; r++)
                {
                    for (int c = 0; c < Landscape.LandUseMap.Ncols; c++)
                    {
                        values[LandUse[r, c]]++;
                    }
                }
                string line = t + "\t";
                for (int l = 0; l < Landscape.LandUseNames.Length; l++) line += values[l] + "\t";
                Content.Add(line);

                t += int.Parse(Settings.Get(KeyWords.TimeStep));
            }
            System.IO.File.WriteAllLines(filename, Content.ToArray());
        }

         

        public static void WriteMassDistributions(string variable)
        {
            Matrix[] Distributions = FrequencyDistributions.GetDistributions(10, variable);
            for (int l = 0; l < Landscape.LandUseNames.Length; l++)
            {
                string filename = OutputFileName(Settings.Get(KeyWords.Scenarioname), "Distributions", Landscape.LandUseNames[l] + variable);

                System.Console.WriteLine("Writing\t" + filename);

                Distributions[l].Write(filename);
          
            }
            
            
            
        }
        public static void WriteMassSums(string variable)
        {
            string filename = OutputFileName(Settings.Get(KeyWords.Scenarioname), "LandUseSums", variable);
            System.Console.WriteLine("Writing\t" + filename);
            List<string> Content = new List<string>();
            string hdr = "Time\t";
            foreach (string l in Landscape.LandUseNames) hdr += l + "\t";
            Content.Add(hdr);

            int t = 0;
            while(t<=int.Parse(Settings.Get(KeyWords.TimeStep)))
            {
                float[] values = new float[Landscape.LandUseNames.Length];
                ASCII LandUse = new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), KeyWords.LandUse, KeyWords.LandUse, t));
                ASCII Mass = new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), variable, variable, t));

                for (int r = 0; r < Landscape.LandUseMap.Nrows; r++)
                {
                    for (int c = 0; c < Landscape.LandUseMap.Ncols; c++)
                    {
                        values[LandUse[r, c]] += Mass[r, c];
                    }
                }
                string line = t + "\t";
                for (int l = 0; l < Landscape.LandUseNames.Length; l++) line += values[l] + "\t";
                Content.Add(line);
                t += int.Parse(Settings.Get(KeyWords.TimeStep));
            }
            System.IO.File.WriteAllLines(filename, Content.ToArray());
        }
        public static void WriteOutput(int LandscapeYear)
        {
            try
            {
                CO2FixSimulations.Co2year.Write(OutputFileName(Settings.Get(KeyWords.Scenarioname), KeyWords.Co2Year, KeyWords.Co2Year, LandscapeYear));
                Landscape.LandUseMap.Write(OutputFileName(Settings.Get(KeyWords.Scenarioname), KeyWords.LandUse, KeyWords.LandUse, LandscapeYear));
                
                for (int var = 0; var < CO2FixSimulations.VariableLabels.Length; var++)
                {
                    Landscape.Outputvariables[var].Write(OutputFileName(Settings.Get(KeyWords.Scenarioname), CO2FixSimulations.VariableLabels[var], CO2FixSimulations.VariableLabels[var], LandscapeYear));
                }
                
                
            }
            catch (System.Exception e)
            {
                throw new System.Exception("WriteOutput\t"+e.Message);
            }
        }
        public static void ClearFiles(string dir)
        {
            if (System.IO.Directory.Exists(dir) == false) return;
            foreach (string subdir in System.IO.Directory.GetDirectories(dir))
            {
                ClearFiles(subdir);
                try
                {
                    System.IO.Directory.Delete(subdir);
                }
                catch { }
            }
            foreach (string fn in System.IO.Directory.GetFiles(dir))
            {
                System.IO.File.Delete(fn);
            }
        }
        static string Replace(string s)
        {
            s= s.Replace("BushAndShrubs", "BS");
            s=s.Replace("SecondaryForest", "SF");
            s = s.Replace("PrimaryForest", "PF");
            return s;
        }
        public static void WriteRandomSiteOutput(int NumberOfSites = 5)
        {
            int l = 0;
            while(l< Landscape.LandUseNames.Length)
            {
                 ASCII InitialLandUse = new ASCII(Settings.Get("InitialLandUse"));
                 int r = rnd.Next(InitialLandUse.Nrows);
                 int c = rnd.Next(InitialLandUse.Ncols);
                 if (InitialLandUse[r,c] == l)
                 {
                    WriteSiteOutput(r, c);
                    l++;
                    if (l == Landscape.LandUseNames.Length - 1) l = 0;
                 }
            }
        }
        static void WriteSiteOutput(int r, int c)
        {
            string filename = OutputFileName(Settings.Get(KeyWords.Scenarioname), KeyWords.SiteData, "Site[" + r + "," + c + "]");
            System.Console.WriteLine("Writing\t" + filename);
            List<string> Content= new List<string>();
            string hdr = "time\tCO2Fix_time\t";
            foreach (string label in CO2FixSimulations.VariableLabels)
            {
                hdr += label + "\t";
            }
            hdr += "Landuse\tLandUseTransitions";
            Content.Add(hdr);
            
            int LastLandUse = -1;
            for (int t = 0; t < Settings.GetSimulationLength();t++ )
            {
                string line = t + "\t" + new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), KeyWords.Co2Year, KeyWords.Co2Year, t))[r, c] + "\t";
                foreach (string label in CO2FixSimulations.VariableLabels)
                {
                    ASCII a = new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), label, label, t));
                    float v = a[r, c];
                    line+= v+"\t";
                }
                ASCII l = new ASCII(FileName(Settings.Get(KeyWords.Scenarioname), KeyWords.LandUse, KeyWords.LandUse, t));

                line += l[r, c] + "\t";
                if (LastLandUse != l[r, c])
                {
                    if (LastLandUse < 0) line += Replace("T->" + Landscape.LandUseNames[l[r, c]]) + "\t";
                    else line += Replace("T" + Replace(Landscape.LandUseNames[LastLandUse] + "->" + Landscape.LandUseNames[Landscape.LandUseMap[r, c]])) + "\t";
                }
                else line += "" + "\t";
                LastLandUse = l[r, c];
             
                Content.Add(line);
            }
            System.IO.File.WriteAllLines(filename, Content.ToArray());
        }
    }
}
